package com.personnel.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 *
 * @author yuepeng
 * @version 1.0
 * @since 2021-12-28 13:55:41
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 核心拦截方法,在当前服务中的每一次(被拦截的)请求都会调用此方法执行   ps:当用户访问login.html页面时，不会调用此方法，因为我们已经放行
     *
     * @return 返回true代表放行，false代表拦截
     * @throws Exception 异常状态
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //preHandle方法如果返回值为true代表放行，如果返回false代表不放行

        Object user = httpServletRequest.getSession().getAttribute("user");
        if (user == null) {
            //说明用户没有登录过系统重定向到login.html页面
            httpServletResponse.sendRedirect("login.html");  // 这种演示要保证跳转的页面在当前服务器中
            // {code:250, msg:"请登录之后再访问", url:"/login.page"}
            //结束后续的调用
            return false;
        }
        //请求放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
